import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:plain_notification_token/plain_notification_token.dart';

// import 'package:pin_chat/pin_chat.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'UI/Splash.dart';
import 'Util/Global.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  String appId = Platform.isIOS ? "1:55795936896:ios:92adef6df49132130a8065" : "1:55795936896:android:b75734cdf2e8fb840a8065";
  String apiKey = Platform.isIOS ? "AIzaSyBeYRXMeJC4P2cfNFiQRy322bV-xOlttUc" : "AIzaSyAHY_FrR3WDh_yYVhrS5NXoceMOrxZRO3c";
  await Firebase.initializeApp(
      options: FirebaseOptions(apiKey: apiKey, appId: appId, messagingSenderId: "55795936896", projectId: "himessage-6d17b"));

  // await Firebase.initializeApp();
  if (Platform.isIOS) await FirebaseMessaging.instance.requestPermission();
  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true, // Required to display a heads up notification
    badge: true,
    sound: true,
  );
  FirebaseMessaging.onMessage.listen((event) {
    print("onMessage:$event");
  });

  // (iOS Only) Need requesting permission of Push Notification.

  runApp(Splash());

  // PinChat.configure(
  //     clientKey: 'TmpjeU1UY3hZak10WWpnNU9DMDBOalkyTFRoa1lUSXROR0V5WVdKbE9UUXhPVE15LTE2NDAwNzY3OTQ1NTQ=',
  //     serverUrl: 'https://hitutorapp2.imkit.io');

  DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

  if (Platform.isAndroid) {
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    Global.deviceName = '${androidInfo.model}'; // e.g. "Moto G (4)"
    Global.systemVersion = '${androidInfo.version.release}';

    MethodChannel JPushChannel = MethodChannel('JPush');
    Global.JPushRegToken = await JPushChannel.invokeMethod("init");
    print("JPushRegToken:${Global.JPushRegToken}");

    SystemUiOverlayStyle systemUiOverlayStyle =
        SystemUiOverlayStyle(statusBarColor: Colors.transparent, statusBarBrightness: Brightness.dark);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }

  if (Platform.isIOS) {
    IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
    Global.deviceName = '${iosInfo.utsname.machine}'; // e.g. "iPod7,1"
    Global.systemVersion = '${iosInfo.systemVersion}';

    final plainNotificationToken = PlainNotificationToken();
    plainNotificationToken.requestPermission();
    await plainNotificationToken.onIosSettingsRegistered.first;
    Global.APNSToken = await plainNotificationToken.getToken() ?? "";
    print("APNSToken：${Global.APNSToken}");
  }

  String? token = await FirebaseMessaging.instance.getToken();
  Global.firebasetoken = token ?? "";
  print("firebasetoken：${Global.firebasetoken}");
}
